package com.zoe.onelink.logging.biz.context;

import com.zoe.onelink.logging.biz.evaluator.BizLogRootObject;
import com.zoe.onelink.logging.biz.util.BizLogSpELContextUtil;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.ParameterNameDiscoverer;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-10-12
 */
public class BizLogEvaluationContext extends MethodBasedEvaluationContext {

    private static final Method[] UTIL_METHODS = BizLogSpELContextUtil.class.getDeclaredMethods();

    public BizLogEvaluationContext(BizLogRootObject rootObject, Method method, Object[] arguments,
                                   ParameterNameDiscoverer parameterNameDiscoverer, Object result, String errorMsg) {
        //把方法的参数都放到 SpEL 解析的 RootObject 中
        super(rootObject, method, arguments, parameterNameDiscoverer);
        //把 LogRecordContext 中的变量都放到 RootObject 中
        Map<String, Object> variables = BizLogContext.getValMap();
        if (variables != null && variables.size() > 0) {
            for (Map.Entry<String, Object> entry : variables.entrySet()) {
                setVariable(entry.getKey(), entry.getValue());
            }
        }
        // 注册自定义函数
        for (Method utilMethod : UTIL_METHODS) {
            this.registerFunction(utilMethod.getName(), utilMethod);
        }
        //把方法的返回值和 ErrorMsg 都放到 RootObject 中
        this.setVariable("_ret", result);
        this.setVariable("_success", rootObject.isSuccess());
        this.setVariable("_errorMsg", errorMsg);
    }


}
